import React, { useCallback, useEffect, useState } from "react";
import { Form, Button, Input, Select, Checkbox, Space, DatePicker, message, Popconfirm, Image, List } from "antd";

import BatchSuffixInput from "@/views/components/BatchSuffixInput";
import IconFont from "@/components/IconFont";

import { goodsSkuMatch, getZjfGoodsSkuVOList, getMatchSkuListBySpuId, foreignSeniorSearchByUrl } from "../../service";
import { defaultSkuList, getUniqueListByKey } from "../../utils";
import { useSkuColumns } from "./useSkuColumns";
import { cloneDeep } from "lodash";

import CommonZjfImg from "@/views/components/CommonZjfImg";

import VirtualList from "rc-virtual-list";

const searchByUrl = async url => {
	const API_DATA = {
		url
	};
	return await foreignSeniorSearchByUrl(API_DATA);
};
const colWidth = {
	image: "8%",
	colour: "22%",
	storeInfoRender: "54%",
	action: "16%"
};
export const useSkuList = ({ spuId, onDrawerClose }) => {
	const [skuList, setSkuList] = useState([...defaultSkuList]); //第一个表格数据，包含 系统商品sku和 供应商商品sku (系统sku、搜图结果和选择操作)
	const [skuColorList, setSkuColorList] = useState([]); // 系统商品sku， 颜色不重复
	const [skuSizeList, setSkuSizeList] = useState([]); // 系统商品sku， 尺码不重复

	const [matchedStoreSkuAllList, setMatchedStoreSkuAllList] = useState([]); //第一个表格，已匹配的数据
	const [skuColorMatchList, setSkuColorMatchList] = useState([]); // 第一个表格，选择后的颜色匹配关系 {sys, store}

	// 以下数据在 useSkuColumns / useSizeList 需要使用，所以定义在此
	const [sizeSelectTableData, setSizeSelectTableData] = useState([]); //第二个表格数据，包含系统sku尺码、可选的多个供应商商品尺码下拉

	//  渲染 供应商 sku 图片 和 文字
	const storeSkuInfoRender = ({ skuImage, storeId, skuLabel }, style = {}) => {
		return (
			<div className="flex" style={style}>
				<CommonZjfImg img={skuImage} storeId={storeId} />
				<span>{skuLabel}</span>
			</div>
		);
	};

	const checkIsSelected = useCallback(
		item => {
			if (item.isSelected) return true;
			if (item.parentSupplierSkuId) {
				const f = matchedStoreSkuAllList.find(e => e.goodsId == item.parentSupplierSkuId);
				if (f) return f.color == item.skuColor;
			}
			return false;
		},
		[matchedStoreSkuAllList]
	);
	// 渲染 合并行
	const renderMerge = useCallback(
		({ found, items }) => {
			if (!found) return <>抱歉，未搜索出相似图片的商品</>;
			const tdStyle = { padding: "8px 12px" };
			return (
				<List>
					<VirtualList data={items} height={146} itemHeight={48} itemKey="uuid">
						{item => (
							<List.Item key={item.uuid} style={{ padding: "0" }}>
								<div className="flex width-full" key={item.uuid}>
									{/* 图片 空div占位 */}
									<div style={{ width: colWidth.image, ...tdStyle }}></div>
									{/* 颜色 空div占位 */}
									<div style={{ width: colWidth.colour, ...tdStyle }}></div>
									{/* 供应商商品 */}
									{storeSkuInfoRender(item, { width: colWidth.storeInfoRender, ...tdStyle })}
									{/* 操作 */}
									<div style={{ width: colWidth.action, textAlign: "center", ...tdStyle }}>
										{checkIsSelected(item) ? (
											"已选择"
										) : (
											<Button type="link" onClick={() => handleStoreInfoSelectCommand(item, true)}>
												选择
											</Button>
										)}
									</div>
								</div>
							</List.Item>
						)}
					</VirtualList>
				</List>
			);
		},
		[checkIsSelected, storeSkuInfoRender]
	);

	const handleStoreInfoSelectCommand = (item, flag) => {
		if (flag) {
			// 选中
			setSkuList(pre => {
				// item 为供应商sku行数据mergeRow中的items子元素
				return pre.map(skuRow => {
					// 找到 mergeRow, 将选中item 的 isSelected 设为 true，其它false
					if (skuRow.parentSkuId == item.parentSkuId) {
						const mergeRow = skuRow;
						mergeRow.items = mergeRow.items.map(e => {
							return {
								...e,
								isSelected: e.uuid === item.uuid
							};
						});

						return cloneDeep(mergeRow);
					}
					// 找到 系统sku行数据, 将选中项 渲染后 赋值给 storeInfoRender 字段
					if (skuRow.skuId == item.parentSkuId) {
						skuRow.storeInfoRender = storeSkuInfoRender(item, { height: "31px" });

						setSkuColorMatchList(pre => [...pre, cloneDeep({ sys: skuRow, store: item })]);
					}
					return skuRow;
				});
			});
		} else {
			// item 为系统sku行数据

			// 从选择的供应商颜色中删除
			setSkuColorMatchList(pre => {
				return pre.filter(e => e.sys.skuId !== item.skuId);
			});
			// 从已匹配的sku行数据中删除
			setMatchedStoreSkuAllList(pre => {
				return pre.filter(e => e.goodsCommonId != item.supplierSpuCode);
			});
			// 清空
			setSkuList(pre => {
				return pre.map(skuRow => {
					// 找到 mergeRow, 清空 isSelected
					if (skuRow.parentSkuId == item.skuId) {
						const mergeRow = skuRow;
						mergeRow.items = mergeRow.items.map(e => {
							return {
								...e,
								isSelected: false
							};
						});

						return cloneDeep(mergeRow);
					}
					// 找到 系统sku行数据, 清空 storeInfoRender
					if (skuRow.skuId == item.skuId) {
						skuRow.storeInfoRender = null;
					}
					return skuRow;
				});
			});
		}
	};

	const { columns } = useSkuColumns({
		sizeSelectTableData,
		setSizeSelectTableData,
		handleStoreInfoSelectCommand,
		renderMerge,
		colWidth
	});

	useEffect(() => {
		getMatchSkuListBySpuId({ id: spuId }).then(res => {
			const __skuList = res.data.map(e => ({ ...e, uuid: e.skuId, merge: false, storeInfoRender: null }));
			if (__skuList.every(e => e.image && e.colour && e.specs) && __skuList.length) {
				setSkuList(__skuList);

				const __skuColorList = getUniqueListByKey(__skuList, "colour", "supplierId");
				const __skuSizeList = getUniqueListByKey(__skuList, "specs", "supplierId").map(e => {
					// 把已匹配的数据加入分组
					const sizeMatchedSkuList = __skuList
						.filter(ee => ee.specs == e.specs && ee.supplierSkuId)
						.map(({ supplierId, supplierName, supplierSkuId, supplierSpuCode }) => ({
							supplierId,
							supplierName,
							supplierSkuId,
							supplierSpuCode
						}));
					return {
						...e,
						sizeMatchedSkuList
					};
				});

				setSkuSizeList(__skuSizeList);
				setSkuColorList(__skuColorList);

				addSearchUrlResToSkuColorList(__skuColorList);
				// 获取默认配置的sku信息
				const matchedStoreSkuList = __skuList.filter(e => e.supplierSpuCode);
				const matchedStoreSpuIds = matchedStoreSkuList.map(e => e.supplierSpuCode);
				if (matchedStoreSpuIds.length) {
					getZjfGoodsSkuVOList({ goodsCommonIdList: matchedStoreSpuIds }).then(({ data: storeSkuList, success }) => {
						if (success && Array.isArray(storeSkuList)) {
							setMatchedStoreSkuAllList(storeSkuList);
							setSkuList(pre => {
								return pre.map(skuRow => {
									if (!skuRow.merge && skuRow.supplierId) {
										const {
											colorSpecifications,
											colour,
											image,
											skuId,
											skuName,
											specs,
											spuId,
											supplierId,
											supplierName,
											supplierSkuId,
											supplierSpuCode
										} = skuRow;
										const storeItem = storeSkuList.find(e => e.goodsId == supplierSkuId);
										if (storeItem) {
											const { goodsImage, color, size, goodsCommonId, goodsId, goodsName, storeId, storeName } = storeItem;
											skuRow.storeInfoRender = storeSkuInfoRender({
												skuImage: goodsImage,
												storeId,
												skuLabel: `${storeName}/${goodsName}/${color}`
											});
										}
										return cloneDeep(skuRow);
									}
									return skuRow;
								});
							});
						}
					});
				} else {
					console.log("没有已匹配的数据");
				}
			} else {
				message.warning("该商品不支持智能匹配");
				onDrawerClose(null, false);
			}
		});
	}, []);

	const addSearchResultToSkuList = (record, data) => {
		const parentSkuId = record.skuId;
		const parentSupplierSkuId = record.supplierSkuId;
		const { type, seniorSystemGoodsVOS } = data || {};

		let mergeRow = {
			parentSkuId, // 父skuId，对应系统商品SKU
			parentSupplierSkuId, // 父supplierSkuId，对应已匹配的供应商商品SKU
			uuid: record.skuId + "SearchNotFound", // uuid
			merge: true, // 是否合并行（用来展示以图搜款结果）, 偶数行
			found: false, //  以图搜款，是否有返回结果
			items: [] //  以图搜款，返回的sku明细结果
		};

		if (Array.isArray(seniorSystemGoodsVOS)) {
			const items = [];
			seniorSystemGoodsVOS.forEach(e => {
				const { storeName, storeId, goodsCommonId, goodsName, sku } = e;
				const { color, colorImage, size, spec } = sku[goodsCommonId];
				color.map(skuColor => {
					const uuid = record.skuId + skuColor;
					const skuImage = colorImage[skuColor];
					/**
					 * 5、供应商图片：图片是相似供应商sku商品的图片；

6、供应商商品名称：【供应商】+供应商商品spu名称+对应的颜色规格
					 */
					const skuLabel = `${storeName}/${goodsName}/${skuColor}`;

					items.push({
						uuid,
						parentSkuId,
						parentSupplierSkuId,
						skuImage,
						storeId,
						storeName,
						skuColor,
						skuLabel,
						isSelected: false,
						color,
						colorImage,
						size,
						spec,
						goodsCommonId,
						goodsName
					});
				});
			});
			mergeRow = {
				parentSkuId,
				parentSupplierSkuId,
				uuid: record.skuId + "SearchFonded",
				found: true,
				merge: true,
				items: items
			};
		}
		setSkuList(pre => {
			const arr = [];
			pre.forEach(element => {
				arr.push(element);
				if (element.skuId === record.skuId) {
					if (element.storeInfoRender) {
						arr.push(mergeRow);
					} else {
						let lostData = {
							image: "",
							colour: "",
							storeInfoRender: (
								<span>
									<IconFont style={{ fontSize: 20 }} type="icontupiancuowu-copy" />
									<span className="ml10">抱歉未搜索出相似的商品</span>
								</span>
							)
						};
						arr.push(lostData);
					}
				}
			});

			return arr;
		});
	};
	const addSearchUrlResToSkuColorList = async __skuColorList => {
		for (const item of __skuColorList) {
			const { image, skuId } = item;
			if (image) {
				const res = await searchByUrl(image);
				addSearchResultToSkuList(item, res.data);
			}
		}
	};

	const tableKey = "SystemGoodsMatchIntelligentMatchTableSku";
	const searchSimpleTableProps = {
		tableKey,
		rowKey: "uuid",
		// ///
		dataSource: skuList,
		columns,
		footer: false
	};

	return {
		tableKey,
		searchSimpleTableProps,
		skuList,
		skuColorList,
		skuSizeList,
		skuColorMatchList,
		setSkuColorMatchList,
		sizeSelectTableData,
		setSizeSelectTableData,
		matchedStoreSkuAllList,
		setMatchedStoreSkuAllList
	};
};
